// 文件md5加密
import sparkMd5 from "spark-md5";
import axios from "axios";

export function fileMd5(file, url){
    let sparkMD5 = new sparkMd5.ArrayBuffer()
    let reader = new FileReader()
    reader.readAsArrayBuffer(file)
    return new Promise((resolve) => {
        reader.onload = (event) => {
            //获取文件MD5
            let str = event.target.result
            sparkMD5.append(str)
            let md5_str = sparkMD5.end()
            let _obj = {
                valid: md5_str,
                name: file.name,
                transfer_png: 1
            }
            //headers: {'Referer': process.env.NODE_ENV === 'development' ? process.env.VUE_APP_UPLOAD_REFERER : window.location.origin}
            axios.get(url,{params:_obj}).then(res => {
                res.valid = md5_str
                resolve(res)
            })
        }
    })
}
function uploadAxios(formData,config,url){
    return new Promise((resolve,reject) => {
        axios.post(url, formData, config).then(res => {
            if (res.data.result) {
                resolve(res)
            } else {
                reject(res)
            }
        }).catch((e) => {
            reject(e)
        })
    })
}
// 单个上传
export function singleUpload(formData,url,onProgress) {
    let config
    if(onProgress){
        config = {
            onUploadProgress: (e) => {
                e.percent = Math.round(
                    (e.loaded * 100) / e.total
                )
                onProgress(e)
            }
        }
    }
    return new Promise((resolve,reject) => {
        uploadAxios(formData,config,url).then(res => {
            resolve(res.data)
        }).catch(e => {
            reject(e)
        })
    })
}
// 分片上传
export function splitUpload (file,url,onProgress,eachSize) {
    console.log('分片上传',file,url,onProgress,eachSize)
    // eslint-disable-next-line no-async-promise-executor
    return new Promise( async (resolve, reject) => {
        try {
            const chunks = Math.ceil(file.size / eachSize)
            const fileChunks = await splitFile(file, eachSize, chunks)
            let currentChunk = 0
            let cbRes = {};
            for (let i = 1; i <= fileChunks.length; i++) {
                // 服务端检测已经上传到第currentChunk块了，那就直接跳到第currentChunk块，实现断点续传
                if (currentChunk === (i-1)) {
                    // 每块上传完后则返回需要提交的下一块的index
                    let postRes = await postFile(
                        {
                            chunk: i-1,
                            chunks,
                            name: file.name,
                            size: file.size,
                            file: fileChunks[i - 1],
                            eachSize,
                        },
                        onProgress,
                        url
                    )
                    // 根据接口格式判断是否续传
                    let data = postRes.data

                    if(data.result && data.chunk !== undefined){
                        currentChunk = Number(data.chunk) + 1
                    } else if(!data.result){
                        reject(data)
                    } else {
                        cbRes = data
                        resolve(cbRes)
                    }
                }
            }
        } catch (e) {
            reject(e)
        }
    })
}
const postFile = (param, onProgress, url) => {
    const formData = new FormData()
    for (let p in param) {
        formData.append(p, param[p])
    }
    const config = {
        onUploadProgress: (e) => {
            if(param.chunk !== param.chunks -1){
                e.percent = Number((e.loaded/e.total+param.chunk)*(param.eachSize/param.size)*100)
            }else{
                e.percent = Number(((e.loaded/e.total)*((param.size - param.eachSize*param.chunk)/param.size)+param.chunk*param.eachSize/param.size)*100)
            }
            onProgress(e)
        },
    }
    // 实际上传事件
    return uploadAxios(formData,config,url).then(res => res)
}
const splitFile = (file, eachSize, chunks) => {
    return new Promise((resolve, reject) => {
        try {
            setTimeout(() => {
                const fileChunk = []
                for (let chunk = 0; chunks > 0; chunks--) {
                    fileChunk.push(file.slice(chunk, chunk + eachSize))
                    chunk += eachSize
                }
                resolve(fileChunk)
            }, 0)
        } catch (e) {
            console.error(e)
            reject(new Error('文件切块发生错误'))
        }
    })
}
